<template>
  <div>
    <Card>
      <Row class="m-t-sm">
        <Form ref='model' :model="model" :rules="ruleInline" label-position="right" inline :label-width='110'>
          <Row>
            <Col :span="18">
              <Row>
                <Col span="8">
                  <FormItem prop="matchName" label="赛事名称">
                    <Select
                      v-show="isApprove"
                      style="width: 200px"
                      ref="select"
                      v-model="model.matchName"
                      filterable
                      filter-by-label
                      remote
                      clearable
                      :disabled="!isEdit"
                      label-in-value
                      :label="model.matchName"
                      @on-clear="clearValue"
                      @on-select="selectChange"
                      :remote-method="remoteMethod"
                      :loading="isLoading">
                      <Option v-for="(option, index) in options"  :value="option.label" :key="index">{{option.label}}</Option>
                    </Select>
                    <Input  v-show="!isApprove" v-model="model.matchName" style="width:200px" placeholder="请输入" :disabled="!isEdit" clearable @on-clear="clearValue"/>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem prop='adress' label="地址">
                    <Cascader v-if="isAdress" v-model="model.adress" :disabled="isApprove||!isEdit"  change-on-select style="width:200px;"  :data="adressData" :load-data="loadData"></Cascader>
                    <span v-else style="color: #9b9b9b">暂无地址</span>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem  label="球员类型">
                    <Select
                      style="width: 200px"
                      ref="select"
                      v-model="type"
                      clearable>
                      <Option v-for="(option, index) in optionType"  :value="option.value" :key="index">{{option.label}}</Option>
                    </Select>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span="8" v-show="isApprove">
                  <FormItem prop="kindCode" label="赛事类型">
                    <Select
                      style="width: 200px"
                      v-model="model.kindCode"
                      disabled>
                      <Option v-for="(option, index) in options" :value="option.kindCode" :key="index">{{option.kindCodes}}</Option>
                    </Select>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem prop="startTime" label="计划开始时间">
                    <DatePicker type="date" placeholder="请选择" :options="opStartTime" style="width:200px; " :disabled="isApprove||!isEdit" v-model="model.startTime"></DatePicker>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem prop="endTime" label="计划结束时间">
                    <DatePicker type="date" :options="opEndTime"  placeholder="请选择" style="width:200px;" :disabled="isApprove||!isEdit" v-model="model.endTime"></DatePicker>
                  </FormItem>
                </Col>
                <Col span="8"  v-show="isApprove">
                  <FormItem prop='entryQuota' label="参赛名额">
                    <InputNumber :disabled="!isEdit" v-model="model.entryQuota" :max="10000" :min="1" :precision="0" placeholder="请输入" style="width:200px;"></InputNumber>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem prop='matchMoney' label="参赛费用">
                    <InputNumber :disabled="!isEdit" v-model="model.matchMoney" :max="10000" :min="0" :precision="0" placeholder="请输入" style="width:200px;"></InputNumber>
                  </FormItem>
                </Col>
              </Row>
              <Row v-if="!isApprove">
                <Col span="8">
                  <FormItem prop='quotaTeenageABoy' label="青少年男子A组参赛名额" >
                    <InputNumber :disabled="!isEdit" v-model="model.quotaTeenageABoy" :max="10000" :min="0" :precision="0" placeholder="请输入" style="width:200px;"></InputNumber>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem prop='quotaTeenageBBoy' label="青少年男子B组参赛名额" >
                    <InputNumber :disabled="!isEdit" v-model="model.quotaTeenageBBoy" :max="10000" :min="0" :precision="0" placeholder="请输入" style="width:200px;"></InputNumber>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem prop='quotaTeenageCBoy' label="青少年男子C组参赛名额" >
                    <InputNumber :disabled="!isEdit" v-model="model.quotaTeenageCBoy" :max="10000" :min="0" :precision="0" placeholder="请输入" style="width:200px;"></InputNumber>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem prop='quotaTeenageAGirl' label="青少年女子A组参赛名额" >
                    <InputNumber :disabled="!isEdit" v-model="model.quotaTeenageAGirl" :max="10000" :min="0" :precision="0" placeholder="请输入" style="width:200px;"></InputNumber>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem prop='quotaTeenageBGirl' label="青少年女子B组参赛名额" >
                    <InputNumber :disabled="!isEdit" v-model="model.quotaTeenageBGirl" :max="10000" :min="0" :precision="0" placeholder="请输入" style="width:200px;"></InputNumber>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem prop='quotaTeenageCGirl' label="青少年女子C组参赛名额">
                    <InputNumber :disabled="!isEdit" v-model="model.quotaTeenageCGirl" :max="10000" :min="0" :precision="0" placeholder="请输入" style="width:200px;"></InputNumber>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem prop='amateurBoy' label="业余男子参赛名额" >
                    <InputNumber :disabled="!isEdit" v-model="model.amateurBoy" :max="10000" :min="0" :precision="0" placeholder="请输入" style="width:200px;"></InputNumber>
                  </FormItem>
                </Col>
                <Col span="8">
                  <FormItem prop='amateurGirl' label="业余女子参赛名额">
                    <InputNumber :disabled="!isEdit" v-model="model.amateurGirl" :max="10000" :min="0" :precision="0" placeholder="请输入" style="width:200px;"></InputNumber>
                  </FormItem>
                </Col>
              </Row>
            </Col>
            <Col :span="6">
              <FormItem prop="logo" style="width:90%;" label="赛事图片">
                <upload-logo :disabled="!isEdit" :value="model.logo" :isDefault="isDefault" @upload="upload"></upload-logo>
              </FormItem>
            </Col>
          </Row>
          <Row>
            <FormItem prop="content" style="width:89%;" label="通知内容">
              <editor ref="editor" v-show="isEdit" :value="model.content" @on-change="handleChange"/>
              <Card v-show="!isEdit">
                <span v-html="$config.decodeHtml(model.content)"></span>
              </Card>
            </FormItem>
          </Row>
          <Row>
            <FormItem prop='attachment' label="赛事规程上传：">
              <upload-excel-word @upload="getFieldData" :isEdit="isEdit" @deleteUrl="cutBack" :value="model.attachment" :attachmentPdf="pdf" :pdfArr="pdfArr"></upload-excel-word>
            </FormItem>
          </Row>
          <Row style="text-align: right">
            <div v-if="isEdit">
              <Button @click="cancel" class="m-l-sm">取消</Button>
              <Button @click="save" type="primary" class="m-l-sm">保存</Button>
            </div>
            <div v-else>
              <Button @click="cancel" type="primary" class="m-l-sm">返回</Button>
            </div>
          </Row>

        </Form>
      </Row>
    </Card>
    <Modal title="图片预览" v-model="visible" class="modal-img-view">
      <img :src="imgUrl" style="width: 100%;">
      <div slot="footer"></div>
    </Modal>
  </div>
</template>
<script>
  import dictSpan from "_c/dict/dict-span.vue";
  import Editor from "_c/editor";
  import { addOne,matchPdf,getOne,getEvents,dict } from '@/api/applets';
  import uploadExcelWord from "_c/upload/upload-excel-word.vue";
  import uploadLogo from "_c/upload/upload-logo.vue";
  export default {
    components: {
      dictSpan,
      Editor,
      uploadExcelWord,
      uploadLogo
    },
    data() {
      return {
        isDefault:!this.$route.query.id,
        isEdit:this.$route.query.edit === '1',
        isApprove: this.$route.query.type === '1',
        isLoading:false,
        model: {
          logo:'',
          matchName: '',
          entryQuota: 1,
          startTime: '',
          endTime: '',
          content: '',
          attachment: '',
          attachmentName:'',
          attachmentPdf: '',
          niandu:'',
          kindCode:'',
          adress:[],
          quotaTeenageABoy:0,
          quotaTeenageBBoy:0,
          quotaTeenageCBoy:0,
          quotaTeenageAGirl:0,
          quotaTeenageBGirl:0,
          quotaTeenageCGirl:0,
          amateurBoy:0,
          amateurGirl:0,
          matchMoney:0,
        },
        adressData:[],
        pdfArr:[],
        pdf:{},
        ruleInline: {
          matchName: [{ required: true, message: "内容不能为空" }],
          // entryQuota: [{ required: true,type:'number', message: "请输入",min: 0, trigger: 'change' }],
          startTime: [{ required: true, message: "请选择" }],
          endTime: [{ required: true, message: "请选择" }],
          logo: [{ required: true, message: "请选择" }],
          matchMoney: [{ required: true,type:'number', message: "请选择",min: 0, trigger: 'change' }],
        },
        opStartTime:{
          disabledDate(date) {
            return date && date.valueOf() < Date.now() - 86400000;
          }
        },
        opEndTime: {
          disabledDate: date => {
            let self = this;
            return (
              date &&
             self.model.startTime && (self.model.startTime.valueOf() >date.valueOf())
            );
          }
        },
        visible:false,
        imgUrl:'',
        options:[],
        kindCodes:'',
        countryParam: {
          dictCode: 'AG_IN',
          parentCode:''
        },
        selectItem:{},
        isAdress:true,
        type:'',
        optionType:[
          {
            label:'冠军资格',
            value:'1'
          },
          {
            label:'排名资格',
            value:'2'
          },
          {
            label:'公开赛资格',
            value:'3'
          },
          {
            label:'外卡资格',
            value:'4'
          },
        ],
        memberType:JSON.parse(localStorage.getItem('DICT_ZGX_SSDJ'))
      };
    },
     mounted() {
      if(this.$route.query.id){
        this.query()
      }else{
        dict(this.countryParam)
          .then(res => {
            res.forEach(x => {
              x.label = x.name;
              x.value = x.code;
              if(x.hasChildren === '1'){
                x.children = [];
                x.loading = false
              }
            });
            this.adressData = res;
          });
        this.model.logo='/golf/img/2020/08/27/3879145799255040.png'
      }
    },
    methods: {
      loadData (item, callback) {
        item.loading = true;
          this.countryParam.parentCode = item.code;
          dict(this.countryParam)
            .then(res => {
              item.loading = false;
              res.forEach(x => {
                x.label = x.name;
                x.value = x.code;
              });
              if(this.selectItem.fieldAddressCounty){
                this.$set(this.model.adress, 1, this.selectItem.fieldAddressCounty);
              }
              item.children = res;
              callback();
            })
      },
      query() {
         getOne({matchId:this.$route.query.id})
          .then(content => {
            let result = content;
            this.kindCodes = result.kindCode?this.memberType.filter(x => x.code === result.kindCode)[0].name:'';
              dict(this.countryParam)
                .then(res => {
                  res.forEach(x => {
                    x.label = x.name;
                    x.value = x.code;
                    if(x.hasChildren === '1'){
                      x.children = [];
                    }
                  });
                  this.adressData = res;
                  if(result.matchProvince) {
                    this.isAdress = true;
                    this.model.adress = [result.matchProvince];
                    this.countryParam.parentCode = result.matchProvince;
                    if(this.countryParam.parentCode) {
                      dict(this.countryParam)
                        .then(resCity => {
                          resCity.forEach(y => {
                            y.label = y.name;
                            y.value = y.code;
                          });
                          this.adressData.filter(x => x.code === result.matchProvince)[0].children = resCity;
                          this.model.adress = [result.matchProvince,result.matchCity];
                        })
                    }
                  }else{
                    this.isAdress = false;
                  }
                  let num = result.entryQuota.split(',');
                  // console.log(result,'result')
                  this.model = Object.assign({},{
                    matchName: this.isApprove?result.matchName+'('+this.kindCodes+')':result.matchName,
                    entryQuota: +num[result.kindCode-3],
                    startTime: new Date(result.startTime),
                    endTime: new Date(result.endTime),
                    logo: result.logo,
                    content: result.content,
                    attachment: result.attachment,
                    attachmentPdf: result.attachmentPdf,
                    attachmentName: result.attachmentName,
                    pdfNum: result.pdfNum,
                    kindCode:result.kindCode,
                    fieldId: result.fieldId,
                    matchMoney:+result.matchMoney/100,
                    amateurBoy: +num[0],
                    amateurGirl: +num[1],
                    quotaTeenageABoy:+num[2],
                    quotaTeenageAGirl:+num[3],
                    quotaTeenageBBoy:+num[4],
                    quotaTeenageBGirl: +num[5],
                    quotaTeenageCBoy: +num[6],
                    quotaTeenageCGirl: +num[7],
                  });
                  if(this.isApprove) {
                    this.$refs["select"].query = this.model.matchName;
                  }
                  // console.log(this.model.attachment,'this.model.attachment')
                  if(this.model.attachment) {
                    this.pdfArr = this._computedPdf()
                    // console.log(this.pdfArr,'pdfArr')
                  }
                  });
          })
      },
      _computedPdf() {
        let attachmentName = this.$config.getKey(this.model.attachmentName,'name');
        let attachment = this.$config.getKey(this.model.attachment,'url');
        let attachmentPdf = this.$config.getKey(this.model.attachmentPdf,'pdf');
        // let pdfNum = this.$config.getKey(this.model.pdfNum,'pdfNum');
        return attachment.map((item,index) => {
          return {...item, ...attachmentName[index],...attachmentPdf[index]};
        });
      },
      handleChange(html) {
        this.model.content = html;
        this.$refs["model"].validateField("content");
      },
      remoteMethod (query) {
        if (query !== '') {
          this.isLoading = true;
          let param = query.split('(');
          getEvents({fieldName:param[0]})
            .then(res => {
              this.isLoading = false;
              let result = res.list;
                result.forEach(y => {
                  y.kindCodes = this.memberType.filter(x => x.code === y.kindCode)[0].name;
                  y.label = y.fieldName+'('+y.kindCodes+')';
                });
                this.options = this.model.fieldId?result.filter(x => x.fieldId === this.model.fieldId):result;
            })
        } else {
          this.options = [];
          this.model.matchName=""
        }
      },
      clearValue() {
        this.model = {};
        this.model.logo = '/golf/img/2020/08/27/3879145799255040.png';
        this.pdfArr = [];
      },
      selectChange(obj) {
        this.selectItem = this.options.filter(x => x.label === obj.label)[0];
        this.isAdress = !!this.selectItem.fieldAddressProvince;
        this.model = Object.assign({}, {
          startTime: this.selectItem.fieldTime,
          endTime: this.selectItem.fieldEndtime,
          kindCode: this.selectItem.kindCode,
          logo: '/golf/img/2020/08/27/3879145799255040.png',
          entryQuota: 1,
          content: '',
          attachment: '',
          attachmentPdf: '',
          attachmentName: '',
          pdfNum: '',
          adress: this.selectItem.fieldAddressProvince?[this.selectItem.fieldAddressProvince]:[],
          fieldId: this.selectItem.fieldId,
          matchMoney:this.model.matchMoney
        });
        this.pdfArr = [];
      },
      cancel() {
        this.$router.go(-1);
      },
      save() {
        this.$refs["model"].validateField("logo");
        this.model.attachment = this.pdfArr.map(x => x.url).join(',');
        this.model.attachmentName = this.pdfArr.map(x => x.name).join(',');
        this.model.attachmentPdf = this.pdfArr.map(x => x.pdf).join(',');
        this.model.pdfNum = this.pdfArr.map(x => x.pdfNum).join(',');
        this.model.niandu = this.$moment(this.model.endTime).format('YYYY');
        let num = [0,0,0,0,0,0,0,0];
        if(this.model.fieldId){
          num[this.model.kindCode-3] = this.model.entryQuota
        }else {
          num = [this.model.amateurBoy,this.model.amateurGirl,this.model.quotaTeenageABoy,this.model.quotaTeenageAGirl,this.model.quotaTeenageBBoy,this.model.quotaTeenageBGirl,this.model.quotaTeenageCBoy,this.model.quotaTeenageCGirl];
        }
        let param = {
          matchName: this.model.matchName.split('(')[0],
          matchId:this.$route.query.id,
          matchProvince: this.model.adress?this.model.adress[0]:null,
          matchCity:this.model.adress?this.model.adress[1]:null,
          logo:this.model.logo,
          entryQuota: num.join(','),
          startTime: this.model.startTime,
          endTime: this.model.endTime,
          content: this.model.content,
          attachment: this.model.attachment,
          attachmentName:this.model.attachmentName,
          attachmentPdf: this.model.attachmentPdf,
          niandu:this.model.niandu,
          kindCode:this.model.kindCode,
          matchMoney: this.model.matchMoney*100,
          fieldId: this.model.fieldId,
        }
        this.$refs["model"].validate(valid => {
          // console.log(valid,'vaild')
          if(valid) {
            addOne(param)
              .then(res => {
                this.$router.go(-1);
              })
          }
        })
      },
      getVal(expression) {
        let self = this;
        eval(expression);
      },
      // 上传文件成功后发送请求解析
      getFieldData(file) {
        this.pdfArr = file;
        matchPdf({filePath:file[file.length - 1].url})
          .then(res => {
            this.pdf = res;
            let pdfItem = this.pdfArr[this.pdfArr.length - 1].url;
            let fileItem = file[file.length - 1].url;
            if(pdfItem === fileItem) {
              this.pdfArr[this.pdfArr.length - 1].pdf = this.pdf.outPdfPath;
              this.pdfArr[this.pdfArr.length - 1].pdfNum = this.pdf.outPdfNum;
            }
          });
        this.model.attachment = this.pdfArr.map(x => x.url).join(',');
        this.$refs["model"].validateField("attachment");
      },
      cutBack(file) {
        this.pdfArr = file;
      },
      // 获取文件上传地址
      upload(url) {
          this.model.logo = url?url.url:'';
          this.$refs["model"].validateField("logo");
      }
    }
  };
</script>
<style scoped>
  .m-t-sm >>>.ivu-select-dropdown {
  z-index: 99999!important;
}
</style>
